<?php

namespace App\Models\Api;
use App\Exceptions\ApiException;
use App\Models\Api\Base;
use App\Models\Api\Recode;
use App\Models\Api\Orders;
use App\Models\Api\AwardUser;
use Cache;
class Active extends Base
{
    /**大礼包接口
     * 暂时不用后台处理，支付成功后回调
     * @method GET
     * @param array $map
     * @return void
     * @throws ApiException
     */
    public function index($map = [])
    {
        $uid = $map['uid'] ?? 0;
        $gid = $map['gid'] ?? 0;
        $rids = $map['rids'] ?? 0;  //多个档案

        $Recode = new Recode();
        $Orders = new Orders();
        $AwardUser = new AwardUser();
        // 判断活动是否开启
//        $active = checktime();
        $active = false;
        // 检查是否在活动时间内购买的年运
        if ($active && in_array($gid, [24, 25, 26, 27]))
        {
            // 获取当前用户自己的档案id，用于获取赠送运势的数据
            $selfId = $Recode->getSelfRecode(['uid' => $uid]);
            // 给多个档案赠送运势
            foreach ($rids as $r)
            {
                // 获取当前档案已购买的日运订单
                $orders1 = $Orders->fortune_orders(['uid' => $uid, 'rid' => $r, 'type' => 1]);
                // 获取当前档案已购买的日运中奖记录
                $aorders1 = $AwardUser->get_award_fortune(['uid' => $uid, 'rid' => $r, 'type' => 1, 'self_id' => $selfId]);
                // 获取当前档案已购买的月运订单
                $orders2 = $Orders->fortune_orders(['uid' => $uid, 'rid' => $r, 'type' => 2]);
                // 获取当前档案已购买的月运中奖记录
                $aorders2 = $AwardUser->get_award_fortune(['uid' => $uid, 'rid' => $r, 'type' => 3, 'self_id' => $selfId]);

                // 合并当前档案解锁的日运数据
                $day_orders = array_merge($orders1, $aorders1);
                // 合并当前档案解锁的月运数据
                $month_orders = array_merge($orders2, $aorders2);

                // 获取日运解锁范围
                $day_time = [];
                // 获取月运解锁范围
                $month_time = [];
                // 获取重组后的日运解锁范围
                $unlock_time_range_day = [];
                // 获取重组后的月运解锁范围
                $unlock_time_range_month = [];
                // 赠送的日运开始时间 json字符串
                $extend1 = '';
                // 赠送的月运开始时间 json字符串
                $extend2 = '';

                // 若档案有订单或中奖记录，则进行时间重组
                if (($day_orders && !empty($day_orders)) || ($month_orders && !empty($month_orders)))
                {
                    // 若档案有订单，则获取档案解锁时间范围
                    if ($day_orders)
                    {
                        // 获取档案解锁的时间信息
                        foreach ($day_orders as $k => $v)
                        {
                            // 获取日运的订单解锁时间
                            $day_extend = json_decode($v['extend'], true);
                            // 判断当前数据为中奖类型
                            if (isset($day_extend['award_time']) && $day_extend['award_time'])
                            {
                                // 获取日运的中奖解锁时间
                                $day_start_time_award = date('Y-n-j', $day_extend['award_time']);
                                $day_end_time_award = date('Y-n-j', strtotime('-1 days', strtotime($v['expire_time'], $day_extend['award_time'])));
                                $day_unlock_time_award['start_time'] = $day_start_time_award;
                                $day_unlock_time_award['end_time'] = $day_end_time_award;
                                // 获取日运中奖解锁范围
                                $day_time[] = prDates(['start' => $day_unlock_time_award['start_time'], 'end' => $day_unlock_time_award['end_time'], 'type' => 1]);
                            }// 判断当前数据为订单类型
                            else
                            {
                                if (isset($day_extend['expire_time']) && $day_extend['expire_time'])
                                {
                                    $v['expire_time'] = $day_extend['expire_time'];
                                }
                                // 获取日运的中奖解锁时间
                                $day_start_time_orders = date('Y-n-j', $v['time']);
                                $day_end_time_orders = date('Y-n-j', strtotime('-1 days', strtotime($v['expire_time'], $v['time'])));
                                $day_unlock_time_orders['start_time'] = $day_start_time_orders;
                                $day_unlock_time_orders['end_time'] = $day_end_time_orders;
                                // 获取日运订单解锁范围
                                $day_time[] = prDates(['start' => $day_unlock_time_orders['start_time'], 'end' => $day_unlock_time_orders['end_time'], 'type' => 1]);
                            }
                        }
                    }
                    // 若档案有中奖记录，则获取档案中奖时间范围
                    if ($month_orders)
                    {
                        // 获取档案中奖的信息
                        foreach ($month_orders as $k => $v)
                        {
                            $month_extend = json_decode($v['extend'], true);
                            // 判断当前数据为中奖类型
                            if (isset($month_extend['award_time']) && $month_extend['award_time'])
                            {
                                // 获取月运的中奖解锁时间
                                $month_start_time_award = date('Y-n', $month_extend['award_time']);
                                $month_end_time_award = date('Y-n', strtotime('-1 days', strtotime($v['expire_time'], $month_extend['award_time'])));
                                $month_unlock_time_award['start_time'] = $month_start_time_award;
                                $month_unlock_time_award['end_time'] = $month_end_time_award;
                                // 获取月运的中奖解锁范围
                                $month_time[] = prDates(['start' => $month_unlock_time_award['start_time'], 'end' => $month_unlock_time_award['end_time'], 'type' => 2]);
                            } // 判断当前数据为订单类型
                            else
                            {
                                if (isset($month_extend['expire_time']) && $month_extend['expire_time'])
                                {
                                    $v['expire_time'] = $month_extend['expire_time'];
                                }
                                // 获取月运的订单解锁时间
                                $month_start_time_orders = date('Y-n', $v['time']);
                                $month_end_time_orders = date('Y-n', strtotime('-1 days', strtotime($v['expire_time'], $v['time'])));
                                $month_unlock_time_orders['start_time'] = $month_start_time_orders;
                                $month_unlock_time_orders['end_time'] = $month_end_time_orders;
                                // 获取月运订单解锁范围
                                $month_time[] = prDates(['start' => $month_unlock_time_orders['start_time'], 'end' => $month_unlock_time_orders['end_time'], 'type' => 2]);
                            }
                        }
                    }
                    // 将日运解锁的时间范围重组
                    if ($day_time)
                    {
                        foreach ($day_time as $k => $v)
                        {
                            if ($v)
                            {
                                foreach ($v as $vv)
                                {
                                    if ($vv)
                                        $unlock_time_range_day[] = strtotime($vv);
                                }
                            }
                        }
                    }

                    // 将月运解锁的时间范围重组
                    if ($month_time)
                    {
                        foreach ($month_time as $k => $v)
                        {
                            if ($v)
                            {
                                foreach ($v as $vv)
                                {
                                    if ($vv)
                                        $unlock_time_range_month[] = strtotime($vv);
                                }
                            }
                        }
                    }
                    // 将日运解锁时间范围从大到小排序，获取最后解锁的时间
                    if ($unlock_time_range_day)
                    {
                        rsort($unlock_time_range_day);
                        $unlock_time_range_day = date('Y-n-j', explode('-', array_slice($unlock_time_range_day, 0, 1)[0])[0]);
                    }
                    // 将月运解锁时间范围从大到小排序，获取最后解锁的时间
                    if ($unlock_time_range_month)
                    {
                        rsort($unlock_time_range_month);
                        $unlock_time_range_month = date('Y-n', explode('-', array_slice($unlock_time_range_month, 0, 1)[0])[0]);
                    }
                    // 重组赠送的时间
                    if ($unlock_time_range_day)
                    {
                        $extend1 = json_encode(['award_time' => strtotime('+1 days', strtotime($unlock_time_range_day))], true);
                    }
                    if ($unlock_time_range_month)
                    {
                        $extend2 = json_encode(['award_time' => strtotime('+1 months', strtotime($unlock_time_range_month))], true);
                    }
                }
                //赠送的开始时间
                $nowTime = time();

                //若档案无解锁的日期，默认从当前时间开始重组日运赠送的时间
                if (!$extend1)
                {
                    $extend1 = json_encode(['award_time' => strtotime('+1 days', strtotime(date('Y-m-d', $nowTime)))], true);
                }
                //若档案无解锁的日期，默认从当前时间开始重组日运赠送的时间重组月运赠送的时间
                if (!$extend2)
                {
                    $extend2 = json_encode(['award_time' => strtotime('+1 months', strtotime(date('Y-m', $nowTime)))], true);
                }

                //日运的赠送数据
                $arr1 = [
                    'uid' => $uid,
                    'rid' => $r,
                    'extend' => $extend1,
                    'create_time' => $nowTime
                ];
                //月运的赠送数据
                $arr2 = [
                    'uid' => $uid,
                    'rid' => $r,
                    'extend' => $extend2,
                    'create_time' => $nowTime
                ];
                //购买一年运势享受8折优惠，再送每日运势一个月，每月运势一个月。
                //三年运势享受8折优惠，再送每日运势三个月，每月运势三个月。
                //五年运势享受8折优惠，再送每日运势五个月，每月运势五个月。
                //十年运势享受8折优惠，再送一年每日运势与每月运势。
                switch ($gid)
                {
                    case 25:
                        $arr1['aid'] = 4;
                        $arr2['aid'] = 21;
                        break;
                    case 26:
                        $arr1['aid'] = 5;
                        $arr2['aid'] = 22;
                        break;
                    case 27:
                        $arr1['aid'] = 6;
                        $arr2['aid'] = 23;
                        break;
                    default :
                        $arr1['aid'] = 3;
                        $arr2['aid'] = 20;
                        break;
                }
                try
                {
                    //赠送日运
                    $AwardUser->insert($arr1);
                    // 清除赠送的日运的缓存
                    Cache::forget($uid . '_' . $r . '_award_fortune_1');
                    //赠送月运,并加入计算
                    $mid = $AwardUser->insertGetId($arr2);
                    // 清除赠送的月运的缓存
                    Cache::forget($uid . '_' . $r . '_award_fortune_3');
                    // 赠送的月运加入队列
                    $this->push_fortune($mid, $r);
                }
                catch (\Exception $e)
                {
                   \Log::info('用户:' . $uid . '购买年运大礼包时，赠送失败 ' . PHP_EOL . '当前参数为：' . var_export($map, true) . PHP_EOL . $e->getMessage());
                }
            }
        }
        return;
    }


    /**
     * 月运赠送加入队列计算
     * @param int $mid
     * @param int $rid
     * @throws \app\common\lib\exception\ApiException
     */
    public function push_fortune($mid = 0, $rid = 0)
    {
        //赠送的月运id
        $mid = intval($mid);
        //被赠送的档案id
        $rid = intval($rid);

        // 获取当前档案中奖的相关信息
        $data = (new AwardUser())->getAwardForId($mid);
        // 获取当前档案的相关信息
        $recode = (new Recode())->getRecode(['id' => $rid]);

        if (!empty($data))
        {
            // 获取中奖信息中的 获赠的运势时间
            $award_time = json_decode($data['extend'], true)['award_time'];
            // 获赠的运势的结束时间
            $end_time = strtotime('-1 days', strtotime($data['expire_time'], $award_time));
            $datas['type'] = 'month';
            $datas['ftype'] = 3;
            $datas['aid'] = $mid;
            $datas['recode'][] = $recode;

            $start_time = prDates([
                'start' => date('Y-m', $award_time),
                'end' => date('Y-m', $end_time),
                'type' => 2,
            ]);
            $datas['start_time'] = $start_time;
            // 加入队列
            if (!empty($datas))
            {
                $queueConfig = config('queue');

                if (getVip($datas['recode'][0]['uid']) >= 1)
                {
                    $queueConfig['fortune_delay'] = 0;
                }
                queuePush($queueConfig['fortune_task'], $data, $queueConfig['queue'], $queueConfig['fortune_delay']);

//                rabbitTask('fortune',$data);
            }
        }
        return;
    }
}
